package com.yituo.mjworld.mvc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.core.web.core.BaseForm;
import com.yituo.mjworld.core.web.core.Result;
import com.yituo.mjworld.mvc.dao.ProductDao;
import com.yituo.mjworld.mvc.entity.web.Product;
import com.yituo.mjworld.mvc.entity.web.ProductProps;
import com.yituo.mjworld.mvc.entity.web.WebImgArr;
import com.yituo.mjworld.mvc.form.DeleteForm;
import com.yituo.mjworld.mvc.form.QueryForm;
import com.yituo.mjworld.mvc.form.QueryGoods;
import com.yituo.mjworld.mvc.form.SearchForm;
import com.yituo.mjworld.mvc.service.BaseService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

@Service
public class ProductServiceImpl extends BaseService {

  @Autowired
  ProductDao productDao;
  @Autowired
  QiniuServiceImpl qiniuService;


  /**
   * 获取产品
   *
   * @param productId
   * @return
   */
  public Product getProduct(int productId) {
    return (Product) this.baseDao.get(Product.class, productId);
  }

  /**
   * 获取商品列表
   *
   * @param form
   * @return
   */
  @Override
  public JSONObject getList(QueryForm form) {
    QueryGoods queryGoods = (QueryGoods) form;
    String asc = "asc";
    if (!queryGoods.asc) {
      asc = "desc";
    }
    String orderby = null;
    if (queryGoods.type == QueryGoods.BY_ORDER_NUM) {
      orderby = " order by orderNum ";
    } else if (queryGoods.type == QueryGoods.BY_ALL) {
      // 综合
      orderby = " order by clickCount ";
    } else if (queryGoods.type == QueryGoods.BY_CREATEDATE) {
      // 上新
      orderby = " order by createDate ";
    } else if (queryGoods.type == QueryGoods.BY_PRICE) {
      // 价格
      orderby = " order by price ";
    } else if (queryGoods.type == QueryGoods.BY_SALE_NUM) {
      // 销售数量
      orderby = " order by saleNum ";
    }
    String countSql = "select count(id) from product where childId=:childId";
    String sql = "select " +
        " id," +
        " orderNum," +
        " name," +
        " mark," +
        " shoppePrice," +// 商品专柜价
        " salePrice," +// 商品的显示价格
        " num," +
        " saleSum," +
        " imgArrId," +
        " childId," +
        " createDate," +
        " updateDate," +
        " clickCount," +
        " thumbImgUrl " +
        " from product where childId=:childId " + orderby + asc;
    queryGoods.getParam().clear();
    queryGoods.getParam().put("childId", queryGoods.getChildId());
    return this.get(sql, countSql, queryGoods, queryGoods.getParam());
  }

  /**
   * 删除商品
   *
   * @param form
   * @return
   */
  @Override
  public Result delete(DeleteForm form) {
    Result result = new Result();
    Product goods = (Product) baseDao.get(Product.class, form.getId());
    if (goods == null) {
      result.result = false;
      result.msg = "您删除的商品不存在!";
    } else {
      baseDao.delete(Product.class, form.getId());
      result.result = true;
    }
    return result;
  }


  /**
   * 创建默认的图片数组
   */
  public int checkImageArray(int arrayId, int productId) {
    WebImgArr imgArrDB = (WebImgArr) this.baseDao.get(WebImgArr.class, arrayId);
    if (imgArrDB == null) {
      imgArrDB = new WebImgArr();
      imgArrDB.setProductId(productId);
      Serializable id = this.baseDao.save(imgArrDB);
      return Integer.parseInt(id.toString());
    } else {
      return arrayId;
    }
  }

  /**
   * 添加或者更新
   *
   * @param baseForm
   * @return
   */
  @Override
  public Result saveOrUpdate(BaseForm baseForm) throws InvocationTargetException, IllegalAccessException {
    Result result = new Result();
    Product goods = (Product) baseForm;

    //
    goods.setImgArrId(checkImageArray(goods.getId(),goods.getId()));

    Product goods1 = (Product) baseDao.get(Product.class, goods.getId());
    Product goods2 = productDao.getGoodsByName(goods.getName());
    if (goods1 == null) {
      // 新增操作
      if (goods2 == null) {
        goods.setCreateDate(new Date());
        goods.setUpdateDate(new Date());
        goods.setSaleSum(0);
        baseDao.saveOrUpdate(goods);
        result.setResult(true);
      } else {
        result.setResult(false).setMsg("商品名称不能重复!");
      }
    } else {
      if (goods2 != null && goods2.getId() != goods.getId() && !StringUtils.isEmpty(goods1.getThumbImgUrl()) && !goods1.getThumbImgUrl().equals(goods.getThumbImgUrl())) {
        // 无重复标题,且两个url不相等,删除原来的url
        qiniuService.delete(qiniuService.getFileNameForUrl(goods1.getThumbImgUrl()));
      }
      if (goods2 == null) {
        BeanUtils.populate(goods1, goods.getParam());
        goods1.setImgArrId(goods.getImgArrId());
        // 新的名字没有冲突
        goods1.setUpdateDate(new Date());
        baseDao.merge(goods1);
        result.setResult(true);
      } else {
        if (goods2.getId() == goods.getId()) {
          BeanUtils.populate(goods1, goods.getParam());
          goods1.setImgArrId(goods.getImgArrId());
          // 正常数据,直接更新
          goods.setUpdateDate(new Date());
          baseDao.merge(goods1);
          result.setResult(true);
        } else {
          // 更新后的名字有冲突
          result.setResult(false).setMsg("您修改的名称和其他商品的名称重复!");
        }
      }
    }
    return result;
  }

  /**
   * 搜索
   *
   * @param form
   * @return
   */
  public JSONObject search(SearchForm form) {
    String countSql;
    String sql;
    countSql = "select count(id) from product where name like '%" + form.key + "%'";
    sql = "select " +
        " a.id as id," +
        " a.orderNum as orderNum," +
        " a.name as name," +
        " a.mark as mark," +
        " a.shoppePrice as shoppePrice," +
        " a.salePrice as salePrice," +
        " a.num as num,  " +
        " a.saleSum as saleSum," +
        " a.imgArrId as imgArrId," +
        " a.createDate as createDate," +
        " a.updateDate updateDate," +
        " a.thumbImgUrl as thumbImgUrl," +
        " b.id as childId," +
        " b.title as childTitle," +
        " c.id as parentId," +
        " c.title as parentTitle " +
        " from product a,web_child_item b , web_parent_item c " +
        " where " +
        " a.name like '%" + form.key + "%' " +
        " and a.childId=b.id " +
        " and b.parentId=c.id ";
    return get(sql, countSql, form, null);
  }

  /**
   * 更新URL
   *
   * @param id
   * @param url
   * @return
   */
  public Result updateUrl(int id, String url) {
    Product item = (Product) baseDao.get(Product.class, id);
    if (item == null) {
      return new Result().setResult(false).setMsg("欲更新的产品不存在!");
    } else {
      if (url.equals(item.getThumbImgUrl())) {
        // 两次更新的内容相等,直接返回
        return new Result().setResult(true);
      }
      if (!StringUtils.isEmpty(item.getThumbImgUrl())) {
        // 之前的图片不为空,删除之前的图片
        qiniuService.delete(qiniuService.getFileNameForUrl(item.getThumbImgUrl()));
      }
      item.setThumbImgUrl(url);
      baseDao.saveOrUpdate(item);
    }
    return new Result().setResult(true);
  }

  /**
   * 产品是否存在
   *
   * @return
   */
  public boolean productIsExits(int productId) {
    Product product = (Product) this.baseDao.get(Product.class, productId);
    if (product == null) {
      return false;
    }
    return true;
  }

  /**
   * 产品是否存在
   *
   * @return
   */
  public boolean templateIsExits(int templateId) {
    ProductProps props = (ProductProps) this.baseDao.get(ProductProps.class, templateId);
    if (props == null) {
      return false;
    }
    return true;
  }


}
